package com.jeesite.modules.config;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.jeesite.common.responseReturn.utils.CommonUtils;

public class OpenidUtils {
	public static Map<String, Object> getOpenId(String code) {
		Map<String, Object> map = new HashMap<String, Object>();
		String status = "1";
		String msg = "ok";
		System.out.println("WeixinConstants.APPID===="+WeixinConstants.APPID);
		System.out.println("WeixinConstants.APP_SECRECT===="+ WeixinConstants.APP_SECRECT);
		String WX_URL = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";
		try {

			if (StringUtils.isBlank(code)) {
				status = "0";// 失败状态
				msg = "code为空";
			} else {
				String requestUrl = WX_URL
						.replace("APPID", WeixinConstants.APPID)
						.replace("SECRET", WeixinConstants.APP_SECRECT)
						.replace("JSCODE", code)
						.replace("authorization_code",
								WeixinConstants.AUTHORIZATION_CODE);
				// o6NL05a8ju_Gq-xbhzf24cbDmKk4
				// 发起GET请求获取凭证
				JSONObject jsonObject = CommonUtils.httpsRequest(requestUrl,
						"GET", null);
				if (jsonObject != null) {
					try {
						map.put("openid", jsonObject.getString("openid"));
						map.put("session_key",
								jsonObject.getString("session_key"));
					} catch (JSONException e) {
						// 获取token失败
						status = "0";
						msg = "code无效";
					}
				} else {
					status = "0";
					msg = "code无效";
				}
			}
			map.put("status", status);
			map.put("msg", msg);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return map;

	}

}
